<template>
  <div class="app">
    <!-- 头部 -->
    <header class="header">
      <img src="https://img.icons8.com/color/48/000000/fish.png" alt="闲鱼Logo" class="logo" />
      <div class="search-bar">
        <input
            type="text"
            placeholder="咸鱼好物"
            v-model="searchQuery"
            @keyup.enter="handleSearch"
        />
        <button class="search-btn" @click="handleSearch">搜索</button>
      </div>
    </header>

    <!-- 导航栏 -->
    <nav class="nav">
      <div v-for="item in navItems" :key="item.id" class="nav-item">
        <img :src="item.icon" alt="" />
        <span>{{ item.text }}</span>
      </div>
    </nav>

    <!-- 主体内容 -->
    <main class="main">
      <!-- 搜索结果或推荐区域 -->
      <section class="recommend">
        <h2>{{ isSearching ? '搜索结果' : '推荐' }}</h2>

        <!-- 搜索筛选栏 -->
        <div v-if="isSearching" class="search-filter">
          <div
              v-for="filter in filters"
              :key="filter.id"
              class="filter-item"
              :class="{ active: activeFilter === filter.id }"
              @click="changeFilter(filter.id)"
          >
            {{ filter.text }}
          </div>
        </div>

        <div class="recommend-container" ref="scrollContainer" @scroll="handleScroll">
          <div class="recommend-list">
            <!-- 无结果提示 -->
            <div v-if="isSearching && !loading && products.length === 0" class="no-results">
              <img src="https://img.icons8.com/ios/100/000000/search-property.png" alt="无结果" />
              <p>没有找到相关商品</p>
              <button @click="resetSearch">返回推荐</button>
            </div>

            <div v-for="product in products" :key="product.id" class="recommend-item" @click="showProductDetail(product)">
              <img
                  :src="getProductImage(product)"
                  alt="商品图片"
                  class="product-image"
                  @error="(e) => {
      e.target.src = DEFAULT_PRODUCT_IMAGE;
      e.target.onerror = null;
    }"
              />
              <div class="recommend-info">
                <span class="title">{{ product.title }}</span>
                <span class="price">¥{{ product.price.toFixed(2) }}</span>
                <span class="seller">{{ product.viewCount }}人浏览</span>
              </div>
            </div>
          </div>

          <!-- 加载状态 -->
          <div v-if="loading" class="loading">
            <div class="spinner"></div>
            加载中...
          </div>

          <!-- 错误提示 -->
          <div v-if="error" class="error">
            加载失败，请重试
            <button @click="fetchProducts">重新加载</button>
          </div>

          <!-- 加载更多 -->
          <div v-if="hasMore && !loading && products.length > 0" class="load-more" @click="loadMore">
            加载更多
          </div>
        </div>
      </section>
    </main>

    <!-- 底部导航 -->
    <footer class="footer">
      <div
          v-for="tab in tabs"
          :key="tab.id"
          class="tab"
          :class="{ active: activeTab === tab.id }"
          @click="navigateTo(tab.path)"
      >
        <img :src="tab.icon" alt="" />
        <span>{{ tab.text }}</span>
      </div>
    </footer>

    <!-- 商品详情对话框 -->
    <div v-if="showDetailDialog" class="dialog-overlay" @click.self="closeDetailDialog">
      <div class="dialog-container">
        <div class="dialog-header">
          <h3>{{ currentProduct?.title || '商品详情' }}</h3>
          <button class="close-btn" @click="closeDetailDialog">×</button>
        </div>

        <div class="dialog-content">
          <!-- 加载状态 -->
          <div v-if="dialogLoading" class="dialog-loading">
            <div class="spinner"></div>
            <p>加载中...</p>
          </div>

          <!-- 商品详情内容 -->
          <div v-else-if="currentProduct" class="product-detail-content">
            <div class="detail-images">
              <img
                  :src="getDialogImage(currentProduct)"
                  alt="商品图片"
                  @error="(e) => e.target.src = DEFAULT_PRODUCT_IMAGE"
              >
            </div>

            <div class="detail-info">
              <div class="detail-price">¥{{ currentProduct.price.toFixed(2) }}</div>
              <div class="detail-desc">{{ currentProduct.description || '暂无描述' }}</div>
              <div class="detail-seller">
                <span>卖家：{{ currentProduct.sellerName || '匿名用户' }}</span>
                <span class="detail-view">{{ currentProduct.viewCount || 0 }}人浏览</span>
              </div>
            </div>
          </div>
        </div>

        <div class="dialog-actions">
          <button class="contact-btn" @click="contactSeller">联系卖家</button>
          <button class="buy-btn" @click="buyProduct">加入购物车</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'

// 创建axios实例
const api = axios.create({
  baseURL: '/api',
  timeout: 10000
})

const getProductImage = (product) => {
  // 优先使用imageUrl字段，如果没有则尝试images字段
  const imageUrl = product.imageUrl || product.images;

  // 如果是有效的URL则使用，否则使用默认图片
  if (imageUrl && typeof imageUrl === 'string' && imageUrl.startsWith('http')) {
    return imageUrl;
  }

  // 这里可以添加更多逻辑，比如处理相对路径等
  return DEFAULT_PRODUCT_IMAGE;
}

// 获取对话框中展示的图片
const getDialogImage = (product) => {
  // 支持多张图片，取第一张
  if (Array.isArray(product.images) && product.images.length > 0) {
    return product.images[0];
  }
  return getProductImage(product);
}

// 请求拦截器
api.interceptors.request.use(
    config => {
      // 可以在这里添加token等
      // config.headers.Authorization = `Bearer ${localStorage.getItem('token')}`
      return config
    },
    error => {
      return Promise.reject(error)
    }
)

const router = useRouter()

// 导航栏数据
const navItems = [
  { id: 1, icon: 'https://img.icons8.com/plumpy/48/000000/used-product.png', text: '二手好物' },
  { id: 2, icon: 'https://img.icons8.com/plumpy/48/000000/smartphone.png', text: '数码3C' },
  { id: 4, icon: 'https://img.icons8.com/plumpy/48/000000/cosmetic-brush.png', text: '美妆护肤' },
  { id: 5, icon: 'https://img.icons8.com/plumpy/48/000000/book.png', text: '图书文具' },
  { id: 6, icon: 'https://img.icons8.com/plumpy/48/000000/sofa.png', text: '家居日用' },
  { id: 7, icon: 'https://img.icons8.com/plumpy/48/000000/baby-bottle.png', text: '母婴用品' },
  { id: 8, icon: 'https://img.icons8.com/plumpy/48/000000/vegetarian-food.png', text: '闲置零食' }
]

// 商品数据相关
const products = ref([])
const loading = ref(false)
const error = ref(false)
const hasMore = ref(true)
const currentPage = ref(1)
const searchQuery = ref('')
const isSearching = ref(false)
const activeFilter = ref('all')
const activeTab = ref(1)
const isLoadingMore = ref(false)

// 筛选条件
const filters = [
  { id: 'all', text: '综合' },
  { id: 'price_asc', text: '价格最低' },
  { id: 'price_desc', text: '价格最高' },
  { id: 'view', text: '浏览量' }
]

// 默认商品图片
const DEFAULT_PRODUCT_IMAGE = 'https://img.freepik.com/free-vector/hand-drawn-flat-design-stack-books_23-2149354566.jpg?w=200'

// 底部标签数据
const tabs = [
  {
    id: 1,
    icon: 'https://img.icons8.com/plumpy/48/000000/fish.png',
    text: '闲鱼',
    path: '/home'
  },
  {
    id: 2,
    icon: 'https://img.icons8.com/plumpy/48/000000/marker.png',
    text: '购物车',
    path: '/cart'
  },
  {
    id: 3,
    icon: 'https://img.icons8.com/plumpy/48/000000/plus-2-math.png',
    text: '买入',
    path: '/boughtorders'
  },
  {
    id: 4,
    icon: 'https://img.icons8.com/plumpy/48/000000/speech-bubble-with-dots.png',
    text: '消息',
    path: '/chat'
  },
  {
    id: 5,
    icon: 'https://img.icons8.com/plumpy/48/000000/user-male-circle.png',
    text: '卖出',
    path: '/soldorders'
  }
]

// 对话框相关
const showDetailDialog = ref(false)
const currentProduct = ref(null)
const dialogLoading = ref(false)
const user = ref(JSON.parse(localStorage.getItem('user') || 'null'))
// 获取商品数据
const fetchProducts = async (reset = false) => {
  if (reset) {
    currentPage.value = 1
    hasMore.value = true
  }

  if (!hasMore.value && !reset) return
  if (loading.value) return

  loading.value = true
  error.value = false

  try {
    const params = {
      page: currentPage.value,
      pageSize: 20,
      keyword: searchQuery.value,
      sort: activeFilter.value === 'all' ? '' : activeFilter.value
    }

    const response = await api.get('/backend/products/search', { params })

    if (reset) {
      products.value = response.data || []
    } else {
      products.value = [...products.value, ...(response.data || [])]
    }

    // 假设返回数据中有total字段表示总数
    if (response.total !== undefined) {
      hasMore.value = products.value.length < response.total
    } else {
      // 如果没有total字段，根据返回数据长度判断
      hasMore.value = (response.data || []).length > 0
    }

    currentPage.value++
  } catch (err) {
    console.error('获取商品数据失败:', err)
    error.value = true
    // 如果是加载更多时出错，保留已有数据
    if (!reset) {
      currentPage.value--
    }
  } finally {
    loading.value = false
    isLoadingMore.value = false
  }
}

// 加载更多
const loadMore = () => {
  if (!isLoadingMore.value) {
    isLoadingMore.value = true
    fetchProducts()
  }
}

// 处理滚动加载更多
const handleScroll = (e) => {
  const container = e.target
  const scrollThreshold = 100

  if (container.scrollHeight - container.scrollTop - container.clientHeight < scrollThreshold) {
    loadMore()
  }
}

// 改变筛选条件
const changeFilter = (filterId) => {
  if (activeFilter.value === filterId) return
  activeFilter.value = filterId
  fetchProducts(true)
}

// 处理搜索
const handleSearch = () => {
  if (!searchQuery.value.trim()) {
    resetSearch()
    return
  }

  if (isSearching.value && searchQuery.value === searchQuery.value) return

  isSearching.value = true
  fetchProducts(true)
}

// 重置搜索
const resetSearch = () => {
  if (!isSearching.value) return

  searchQuery.value = ''
  isSearching.value = false
  activeFilter.value = 'all'
  fetchProducts(true)
}

// 查看商品详情（修改为显示对话框）
const showProductDetail = async (product) => {
  // 如果商品数据完整，直接显示
  if (product.description) {
    currentProduct.value = product
    showDetailDialog.value = true
    return
  }

  // 如果商品数据不完整，请求完整数据
  dialogLoading.value = true
  showDetailDialog.value = true

  try {
    const response = await api.get(`/backend/products/${product.id}`)
    currentProduct.value = response.data
  } catch (err) {
    console.error('获取商品详情失败:', err)
    // 显示已有数据
    currentProduct.value = product
  } finally {
    dialogLoading.value = false
  }
}

// 关闭商品详情对话框
const closeDetailDialog = () => {
  showDetailDialog.value = false
  currentProduct.value = null
}

// 联系卖家
const contactSeller = () => {
  console.log('联系卖家:', currentProduct.value?.sellerId)
  router.push({
    name: 'chatbox', // 使用命名路由
    params: {
      currentUserId: user.value.id,
      otherUserId: currentProduct.value.userId
    }
  })
  closeDetailDialog()
}

// 立即购买
const buyProduct = async () => {
  if (!currentProduct.value) {
    console.error('当前商品不存在');
    return;
  }
  try {
    // 创建订单数据
    const orderData = {
      buyerId: user.value.id, // 假设当前用户ID为1，实际应用中应从用户状态获取
      sellerId: currentProduct.value.userId, // 卖家ID从商品信息获取
      productId: currentProduct.value.id, // 商品ID
      amount: currentProduct.value.price, // 订单金额
      status: 0, // 0表示未付款状态
      address: "默认地址", // 固定地址
      contactPhone: "00000000000", // 固定电话
      remark: "立即购买" // 可选备注
    };
    console.log(currentProduct.value)
    // 发送创建订单请求
    const response = await api.post('/backend/order/create', orderData);
    if (response.data && response.data.success) {
    } else {
    }
  } catch (error) {
    console.error('创建订单时出错:', error);

  } finally {
    closeDetailDialog();
  }
}

// 底部导航跳转
const navigateTo = (path) => {
  // 如果对话框打开，先关闭
  if (showDetailDialog.value) {
    closeDetailDialog()
  }
  router.push(path)
}

// 初始化加载数据
onMounted(() => {
  fetchProducts()
})
</script>

<style scoped>
.app {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 50px);
  overflow: hidden;
  background-color: #f5f5f5;
}

.header {
  display: flex;
  align-items: center;
  padding: 10px;
  background-color: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.logo {
  width: 30px;
  height: 30px;
  margin-right: 10px;
}

.search-bar {
  flex-grow: 1;
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 20px;
  padding: 5px 10px;
}

.search-bar input {
  border: none;
  background-color: transparent;
  flex-grow: 1;
  outline: none;
  font-size: 14px;
  width: 100%;
}

.search-btn {
  background-color: #ffda44;
  border: none;
  border-radius: 15px;
  padding: 5px 15px;
  margin-left: 8px;
  font-size: 12px;
  cursor: pointer;
  white-space: nowrap;
}

.nav {
  display: flex;
  justify-content: space-around;
  background-color: white;
  padding: 10px 0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  flex-wrap: wrap;
}

.nav-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 20%;
  margin: 5px 0;
}

.nav-item img {
  width: 30px;
  height: 30px;
}

.nav-item span {
  font-size: 12px;
  margin-top: 5px;
}

.main {
  flex: 1;
  overflow: hidden;
  padding: 10px;
}

.recommend {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.recommend h2 {
  font-size: 16px;
  margin: 10px 0;
  color: #333;
}

.search-filter {
  display: flex;
  background-color: white;
  border-radius: 8px;
  padding: 8px;
  margin-bottom: 10px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.filter-item {
  flex: 1;
  text-align: center;
  font-size: 12px;
  padding: 5px 0;
  cursor: pointer;
}

.filter-item.active {
  color: #ff5000;
  font-weight: bold;
  position: relative;
}

.filter-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 20%;
  right: 20%;
  height: 2px;
  background-color: #ff5000;
}

.recommend-container {
  flex: 1;
  overflow-y: auto;
  scrollbar-width: none;
}

.recommend-container::-webkit-scrollbar {
  display: none;
}

.recommend-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
  padding-bottom: 20px;
}

.recommend-item {
  background-color: white;
  border-radius: 10px;
  padding: 10px;
  display: flex;
  cursor: pointer;
  transition: all 0.2s;
}

.recommend-item:active {
  background-color: #f9f9f9;
}

.product-image {
  width: 80px;
  height: 80px;
  margin-right: 10px;
  object-fit: cover;
  background-color: #f0f0f0;
  border-radius: 8px;
}

.recommend-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.title {
  font-size: 14px;
  margin-bottom: 5px;
  color: #333;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.price {
  font-weight: bold;
  color: #ff5000;
  margin-bottom: 5px;
  font-size: 16px;
}

.seller {
  font-size: 12px;
  color: #999;
}

.no-results {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px 0;
  color: #999;
}

.no-results img {
  width: 100px;
  height: 100px;
  margin-bottom: 20px;
  opacity: 0.6;
}

.no-results p {
  margin-bottom: 15px;
}

.no-results button {
  background-color: transparent;
  border: 1px solid #ff5000;
  color: #ff5000;
  border-radius: 15px;
  padding: 5px 15px;
  font-size: 12px;
  cursor: pointer;
}

.loading, .error {
  text-align: center;
  padding: 15px;
  color: #999;
  font-size: 14px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.spinner {
  width: 20px;
  height: 20px;
  border: 2px solid #f3f3f3;
  border-top: 2px solid #ff5000;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 5px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.error {
  color: #ff5000;
}

.error button, .load-more {
  margin-top: 10px;
  background-color: transparent;
  border: 1px solid #ff5000;
  color: #ff5000;
  border-radius: 15px;
  padding: 5px 15px;
  font-size: 12px;
  cursor: pointer;
}

.load-more {
  border: none;
  background-color: #f5f5f5;
  color: #666;
  margin: 15px 0;
}

.footer {
  display: flex;
  justify-content: space-around;
  background-color: white;
  padding: 8px 0;
  box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
}

.tab {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  font-size: 12px;
}

.tab img {
  width: 25px;
  height: 25px;
}

.tab.active {
  color: #ff5000;
}

.tab.active img {
  filter: invert(42%) sepia(93%) saturate(1352%) hue-rotate(355deg) brightness(104%) contrast(104%);
}

/* 对话框样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 100;
}

.dialog-container {
  background-color: white;
  border-radius: 15px;
  width: 90%;
  max-width: 500px;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #eee;
  position: relative;
}

.dialog-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
  text-align: center;
  flex: 1;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  color: #999;
  cursor: pointer;
  position: absolute;
  right: 15px;
}

.dialog-content {
  flex: 1;
  overflow-y: auto;
  padding: 15px;
}

.dialog-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: #999;
}

.product-detail-content {
  display: flex;
  flex-direction: column;
}

.detail-images {
  margin-bottom: 15px;
}

.detail-images img {
  width: 100%;
  height: 250px;
  object-fit: cover;
  border-radius: 10px;
}

.detail-info {
  display: flex;
  flex-direction: column;
}

.detail-price {
  font-size: 24px;
  font-weight: bold;
  color: #ff5000;
  margin-bottom: 10px;
}

.detail-desc {
  font-size: 14px;
  color: #666;
  margin-bottom: 15px;
  line-height: 1.5;
}

.detail-seller {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  color: #999;
}

.dialog-actions {
  display: flex;
  padding: 15px;
  border-top: 1px solid #eee;
}

.contact-btn, .buy-btn {
  flex: 1;
  padding: 10px;
  border: none;
  border-radius: 25px;
  font-size: 16px;
  cursor: pointer;
  margin: 0 5px;
}

.contact-btn {
  background-color: white;
  color: #ff5000;
  border: 1px solid #ff5000;
}

.buy-btn {
  background-color: #ff5000;
  color: white;
}
</style>